<template>
  <el-upload
    ref="refUpload"
    v-model:file-list="fileList"
    :action="action"
    :headers="uploadHeaders"
    :name="props.name"
    :accept="props.accept"
    :limit="props.limit"
    :before-upload="beforeUpload"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    :="$attrs"
  >
    <slot />
    <template #tip>
      <slot name="tip" />
    </template>
  </el-upload>
</template>

<script setup>
import { getUmsToken } from '@/utils/cookies'

const props = defineProps({
  name: {
    type: String,
    default: 'file'
  },
  accept: {
    type: String,
    default: '.xlsx,.xls'
  },
  limit: {
    type: Number,
    default: 1
  },
  maxSize: {
    type: Number,
    default: 1024 * 1024 * 20
  }
})

const emit = defineEmits([
  'before-upload',
  'on-exceed',
  'on-success',
  'on-remove'
])

const refUpload = ref(null)
const fileList = defineModel('fileList', {
  type: Array,
  default: () => []
})
const action = ref(import.meta.env.VITE_APP_BASE_API + '/file/upload')
const uploadHeaders = {
  Authorization: 'Bearer ' + getUmsToken(),
  lang: g_https.headersLang(),
  timeout: 10000
}

const beforeUpload = file => {
  let isFile = false
  // 判断是否是规定的上传文件
  if (
    !props.accept ||
    props.accept === '*' ||
    props.accept.indexOf('/*') > -1
  ) {
    isFile = true
  } else {
    isFile = props.accept.split(',').some(item => file.name.includes(item))
  }
  // 超过最大限制
  const isLtMaxSize = file.size <= props.maxSize
  if (!isFile) {
    ElMessage.error(
      g_t('rule.uploadFileTip', {
        suffix: props.accept
      })
    )
  } else if (!isLtMaxSize) {
    ElMessage.error(
      g_t('rule.uploadSizeTip2', {
        max: g_utils.transformByteData(props.maxSize)
      })
    )
  }
  emit('before-upload', isFile && isLtMaxSize)
  return isFile && isLtMaxSize
}

const handleRemove = (file, fileList) => {
  emit('on-remove', file, fileList)
}

const handleExceed = (files, fileList) => {
  ElMessage.warning(
    g_t('rule.uploadNumLargeTips2', {
      limit: props.limit
    })
  )
  emit('on-success', files, fileList)
}

const handleSuccess = (res, file, files) => {
  if (res.code === '200' && res.data) {
    ElMessage.success(res.message)
  } else {
    refUpload.value.clearFiles()
    ElMessage({
      message: res.message,
      type: 'error'
    })
  }
  emit('on-success', res, file, files)
}
</script>
